/*
登录场景的主要逻辑
*/
var pomeloClient = require("pomeloClient");
// require("pomeloClient");
var confige = require("confige");
require("localSetting");
require("gvoice");
require("tools");
require("global");

cc.Class({
    extends: cc.Component,

    properties: {
    },

    // use this for initialization
    onLoad: function () {
        pomeloClient();
        window.localSetting.initData();

        window.clientGlobal.tipsWord = cc.find("tipsWord");
        cc.game.addPersistRootNode(window.clientGlobal.tipsWord);
        window.clientGlobal.tipsBox = cc.find("tipsBox").getComponent("tipsBox");
        cc.game.addPersistRootNode(window.clientGlobal.tipsBox.node);
        window.clientGlobal.loadingNode = cc.find("loadingNode").getComponent("tipsBox");
        cc.game.addPersistRootNode(window.clientGlobal.loadingNode.node);
        // var loadNode = cc.find('loadNode').getComponent('loadNode');
        // loadNode.onInit();
        // loadNode.hideNode();
        var btnTest = cc.find("btnTest");
        cc.game.addPersistRootNode(btnTest);
        var showCallBack = function(){
            console.log("showCallBack!!!!!!!!!!!");
            pomelo.disconnect();
        };
        btnTest.on(cc.Node.EventType.TOUCH_END, showCallBack, this);

        this.gameStartBg = cc.find("gameStartBg");
        if(cc.sys.platform == cc.sys.ANDROID)
            this.showGameStart();
        else
            this.gameStartBg.active = false;

        window.clientGlobal.exitBox = cc.find("exitBox").getComponent("tipsBox");
        cc.game.addPersistRootNode(window.clientGlobal.exitBox.node);
        if(cc.sys.platform == cc.sys.ANDROID)
        {
            cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, (event) => {
                switch (event.keyCode)
                {
                    case cc.KEY.back:
                        var nowTime = new Date().getTime();
                        var clickTimeDelay = nowTime - window.clientGlobal.exitLastClickTime;
                        if(clickTimeDelay > 1000)
                            window.clientGlobal.exitClickCount = 1;
                        else
                            window.clientGlobal.exitClickCount++;

                        window.clientGlobal.exitLastClickTime = nowTime;
                        if(window.clientGlobal.exitClickCount == 2)
                        {
                            console.log("back key pressed");
                            window.clientGlobal.exitBox.setTipsType(2,"即将退出游戏!",function(){
                                window.clientGlobal.exitBox.hideLayer();
                                window.clientGlobal.exitClickCount = 0;
                            },function(){
                                cc.director.end();
                            });
                        }
                    break;
                }
            });
        }

        pomelo.clientScene = this;
        confige.curSceneIndex = 0;
        confige.curReconnectType = confige.ON_LOGIN;
        this.editBox = this.node.getChildByName("editBox");
        this.editBox.active = false;
        
        this.btn_loginNode2 = this.node.getChildByName("weChatLogin");
        this.btn_login2 = this.btn_loginNode2.getComponent("cc.Button");
        
        // this.loadingLayer = this.node.getChildByName("loadingLayer").getComponent("loadingLayer");
        // this.loadingLayer.onInit();

        console.log("curUsePlatform === " + cc.sys.platform);
        if(cc.sys.platform == cc.sys.DESKTOP_BROWSER)
        {
            confige.curUsePlatform = 0;
            this.editBox.active = true;
            this.btn_loginNode2.active = false;
            console.log("cc.sys.platform == cc.sys.DESKTOP_BROWSER");
        }else if(cc.sys.platform == cc.sys.ANDROID){
            confige.curUsePlatform = 1;
            console.log("cc.sys.platform == cc.sys.ANDROID");
        }else if(cc.sys.platform == cc.sys.IPHONE || cc.sys.platform == cc.sys.IPAD){
            confige.curUsePlatform = 2;
            console.log("cc.sys.platform == cc.sys.IPHONE");
        }else if(cc.sys.platform == cc.sys.MOBILE_BROWSER){
            confige.curUsePlatform = 3;
            // this.h5LoginError = this.node.getChildByName("h5LoginError");
            this.editBox.active = true;
            this.btn_loginNode2.active = false;

            confige.loginType = 2;

            var RequestData = {};
            RequestData = this.GetRequest();
            console.log("打印url参数!!!!!");
            console.log(RequestData);
            if(RequestData.code)
            {
                if(RequestData.state && RequestData.state != "STATE")
                {
                    //0:hall;1:user;2:game;
                    confige.h5SceneID = parseInt(RequestData.state.substring(0,1));
                    if(confige.h5SceneID == 2)
                        confige.h5RoomID = RequestData.state.substring(2,RequestData.state.length);
                    // if(confige.h5SceneID == 4)
                        // confige.h5CardID = parseInt(RequestData.state.substring(2,RequestData.state.length));
                }

                confige.curUseCode = RequestData.code;
                confige.loginType = 2;
                pomelo.clientLogin(-1,-1);
            }
        }
        
        this.initLocalData();
        this.initAudio();

        // this.versionError = this.node.getChildByName("versionError");
        // this.versionNum = this.node.getChildByName("versionNum").getComponent("cc.Label");
        // this.versionNum.string = confige.versionCheck.split("&")[0];

        cc.sys.localStorage.setItem('currentVersion',confige.curVersion);

        this.updateLayer = this.node.getChildByName("updateNode").getComponent("HotUpdate");
        this.updateLayer.onInit();

        if (cc.sys.isNative) {
            this.updateLayer.checkUpdate();
        }
    },
    
    start: function () {
       
    },

    GetRequest:function(){
        confige.h5SignURL = location.href;
        console.log("完整路径11111====="+confige.h5SignURL);
        var url = location.search; //获取url中"?"符后的字串
        console.log(url);
        var theRequest = new Object();
        var strs = [];
        if (url.indexOf("?") != -1) {   
           var str = url.substr(1);   
           strs = str.split("&");   
           for(var i = 0; i < strs.length; i ++) {   
              theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);   
           }   
        }   
        return theRequest;
    },

    initLocalData:function(){
        if(cc.sys.localStorage.getItem('check_invite') == null)
        {
            cc.sys.localStorage.setItem('check_invite',false);
        }
        if(cc.sys.localStorage.getItem('firstOpen') == null || cc.sys.localStorage.getItem('firstOpen') == -1)    //首次进入游戏
        {
            cc.sys.localStorage.setItem('firstOpen', false);
            
            var userSetting = {
                musicEnable : true,
                soundEnable : true
            };
            cc.sys.localStorage.setItem('userSetting', JSON.stringify(userSetting));
            confige.firstShowNotice = true;
        }else{
            var userSetting = JSON.parse(cc.sys.localStorage.getItem('userSetting'));
            console.log(userSetting);
            if(userSetting.musicEnable == true)
                confige.musicEnable = true;
            else if(userSetting.musicEnable == false)
                confige.musicEnable = false;

            if(userSetting.soundEnable == true)
                confige.soundEnable = true;
            else if(userSetting.soundEnable == false)
                confige.soundEnable = false;

            if(cc.sys.localStorage.getItem('lastLoginDate') != null)
            {
                var lastLoginDate = JSON.parse(cc.sys.localStorage.getItem('lastLoginDate'));
                var curDate = new Date();
                console.log(lastLoginDate);
                if( curDate.getFullYear() == lastLoginDate.year &&
                    curDate.getMonth()+1 == lastLoginDate.month &&
                    curDate.getDate() == lastLoginDate.day )
                {
                    //console.log("在同一天登陆");
                    confige.firstShowNotice = false;
                }else{
                    //console.log("不在同一天登陆");
                    confige.firstShowNotice = true;
                }    
            }
        }
    },

    loadingFalse:function(){
        return;
        this.btn_loginNode2.active = true;
        this.loadingLayer.hideLoading();
    },

    btn_login_click:function(){
        confige.loginType = 0;
        var editString = this.editBox.getComponent("cc.EditBox").string;
        var id = parseInt(editString);
        pomelo.clientLogin(id);
        window.clientGlobal.loadingNode.showLayer(1,"正在登录中......");
    },

    connectCallBack:function(){
        pomelo.request("connector.entryHandler.getNotify",null, function(data) {
            confige.noticeData = data;
            var newNoticeData = JSON.stringify(data);
            var lastNoticeData = cc.sys.localStorage.getItem('lastNoticeData');
            if(newNoticeData == lastNoticeData)
            {
                console.log("没有新的公告");
            }else{
                console.log("有新的公告");
                confige.firstShowNotice = true;
            }
            cc.sys.localStorage.setItem('lastNoticeData', JSON.stringify(data));
        });
    },

    onBtnWeixinClicked:function(){
        // this.btn_login2.interactable = false;
        if(confige.curUsePlatform == 1 || confige.curUsePlatform == 2)
        {
            confige.loginType = 1;
            var lastLoginCount = 99;
            if(cc.sys.localStorage.getItem("wxLastLoginDay") != null)
            {
                lastLoginCount = window.DKTools.getDayCount() - cc.sys.localStorage.getItem("wxLastLoginDay");
            }
            if(cc.sys.localStorage.getItem('wxRefreshToken') == null || lastLoginCount >= 20 || lastLoginCount < 0)
            {
                if(confige.curUsePlatform == 1)
                {
                    jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "WXLogin", "()V");
                }else if(confige.curUsePlatform == 2){
                    jsb.reflection.callStaticMethod("JSCallOC", "WXLogin"); 
                }
                window.clientGlobal.loadingNode.showLayer(1,"正在登录中......");
            }else{
                confige.wxAppInfo.WX_REFRESH_TOKEN = cc.sys.localStorage.getItem('wxRefreshToken');
                var curRefreshToken = confige.wxAppInfo.WX_REFRESH_TOKEN;
                this.wxRefreshLogin();
            }
        }
    },

    wxLoginJavaCall:function(code){
        var self = this;
        var xmlHttp = this.createXMLHttpRequest();

        var httpCallback = function(){
            self.btn_login2.interactable = true;
            var loginJson = JSON.parse(xmlHttp.responseText);
            confige.wxAppInfo.WX_LOGIN_RETURN = loginJson;
            confige.wxAppInfo.WX_ACCESS_TOKEN = loginJson.access_token;
            confige.wxAppInfo.WX_OPEN_ID = loginJson.openid;
            confige.wxAppInfo.WX_UNIONID = loginJson.unionid;
            confige.wxAppInfo.WX_REFRESH_TOKEN = loginJson.refresh_token;
            pomelo.clientLogin(confige.wxAppInfo.WX_OPEN_ID, confige.wxAppInfo.WX_ACCESS_TOKEN);
            cc.sys.localStorage.setItem("wxRefreshToken",loginJson.refresh_token);
            cc.sys.localStorage.setItem("wxLastLoginDay",window.DKTools.getDayCount());
        };

        this.scheduleOnce(function() {
            confige.wxAppInfo.WX_CODE = code;
            var url = confige.wxAppInfo.access_token_url;
            url = url.replace("APPID", confige.wxAppInfo.APP_ID);
            url = url.replace("SECRET", confige.wxAppInfo.SECRET);
            url = url.replace("CODE", confige.wxAppInfo.WX_CODE);
            // xmlHttp.onreadystatechange = httpCallback;
            xmlHttp.onreadystatechange = function () {
                if (xmlHttp.readyState == 4 && (xmlHttp.status >= 200 && xmlHttp.status <= 207)) {
                    var httpStatus = xmlHttp.statusText;
                    var response = xmlHttp.responseText;
                    httpCallback();
                }
            };
            xmlHttp.open("GET", url, true);// 异步处理返回   
            xmlHttp.setRequestHeader("Content-Type",  
                    "application/x-www-form-urlencoded;");  
            xmlHttp.send();
        }, 0.25);
    },

    wxRefreshLogin:function(){
        var self = this;
        var xmlHttp = this.createXMLHttpRequest();

        var httpCallback = function(){
            var loginJson = JSON.parse(xmlHttp.responseText);
            confige.wxAppInfo.WX_LOGIN_RETURN = loginJson;
            if(loginJson.openid && loginJson.access_token)
            {
                confige.wxAppInfo.WX_ACCESS_TOKEN = loginJson.access_token;
                confige.wxAppInfo.WX_OPEN_ID = loginJson.openid;
                confige.wxAppInfo.WX_REFRESH_TOKEN = loginJson.refresh_token;
                pomelo.clientLogin(confige.wxAppInfo.WX_OPEN_ID, confige.wxAppInfo.WX_ACCESS_TOKEN);
                cc.sys.localStorage.setItem("wxRefreshToken",loginJson.refresh_token);
                window.clientGlobal.loadingNode.showLayer(1,"正在登录中......");
                self.btn_login2.interactable = true;
            }else{
                console.log("refresh error");
                cc.sys.localStorage.setItem("wxRefreshToken",null);
                if(confige.curUsePlatform == 1)
                {
                    jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "WXLogin", "()V");
                }else if(confige.curUsePlatform == 2){
                    jsb.reflection.callStaticMethod("JSCallOC", "WXLogin"); 
                }
                window.clientGlobal.loadingNode.showLayer(1,"正在登录中......");
                self.btn_login2.interactable = true;
            }
        };

        this.scheduleOnce(function() {
            var url = confige.wxAppInfo.refresh_token_url;
            url = url.replace("APPID", confige.wxAppInfo.APP_ID);
            url = url.replace("REFRESH_TOKEN", confige.wxAppInfo.WX_REFRESH_TOKEN);
            // xmlHttp.onreadystatechange = httpCallback;
            xmlHttp.onreadystatechange = function () {
                if (xmlHttp.readyState == 4 && (xmlHttp.status >= 200 && xmlHttp.status <= 207)) {
                    var httpStatus = xmlHttp.statusText;
                    var response = xmlHttp.responseText;
                    httpCallback();
                }
            };
            xmlHttp.open("GET", url, true);// 异步处理返回   
            xmlHttp.setRequestHeader("Content-Type",  
                    "application/x-www-form-urlencoded;");  
            xmlHttp.send();
        }, 0.25);
    },

    createXMLHttpRequest:function() {  
        var xmlHttp;  
        if (window.XMLHttpRequest) {  
            xmlHttp = new XMLHttpRequest();  
            if (xmlHttp.overrideMimeType)  
                xmlHttp.overrideMimeType('text/xml');  
        } else if (window.ActiveXObject) {  
            try {  
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");  
            } catch (e) {  
                try {  
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");  
                } catch (e) {  
                }  
            }  
        } 
        return xmlHttp;  
    },
    
    WXCancle:function(){
        this.btn_loginNode2.active = true;
        this.btn_login2.interactable = true;
        // this.loadingLayer.hideLoading();
    },

    hideLogin:function(){
        this.btn_loginNode2.active = false;
    },

    initAudio:function(){
        cc.loader.loadRes("sound/bgMusic/hallBgm", function (err, audio) {
            window.DKTools.audioEG.audioList["hallBgm"] = audio;
            // if(confige.curSceneIndex < 2)
                // window.DKTools.audioEG.playBg("hallBgm");
        });
        cc.loader.loadRes("sound/bgMusic/gameBgm", function (err, audio) {
            window.DKTools.audioEG.audioList["gameBgm"] = audio;
            if(confige.curSceneIndex == 2)
                window.DKTools.audioEG.playBg("gameBgm");
        });

        cc.loader.loadRes("sound/tips/beginBet0", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_beginBet0"] = audio;
        });
        cc.loader.loadRes("sound/tips/beginBet1", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_beginBet1"] = audio;
        });
        cc.loader.loadRes("sound/tips/betMax0", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_betMax0"] = audio;
        });
        cc.loader.loadRes("sound/tips/betMax1", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_betMax1"] = audio;
        });
        cc.loader.loadRes("sound/tips/betItem", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_betItem"] = audio;
        });
        cc.loader.loadRes("sound/tips/btnClick", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_btnClick"] = audio;
        });
        cc.loader.loadRes("sound/tips/disCard", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_disCard"] = audio;
        });
        cc.loader.loadRes("sound/tips/betPlease", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_betPlease"] = audio;
        });
        cc.loader.loadRes("sound/tips/dice", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_dice"] = audio;
        });
        cc.loader.loadRes("sound/tips/beginChair_0", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_beginChair_0"] = audio;
        });
        cc.loader.loadRes("sound/tips/beginChair_1", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_beginChair_1"] = audio;
        });
        cc.loader.loadRes("sound/tips/beginChair_2", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_beginChair_2"] = audio;
        });
        cc.loader.loadRes("sound/tips/beginChair_3", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_beginChair_3"] = audio;
        });
        cc.loader.loadRes("sound/tips/beginChair_4", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_beginChair_4"] = audio;
        });
        cc.loader.loadRes("sound/tips/beginChair_5", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_beginChair_5"] = audio;
        });
        cc.loader.loadRes("sound/tips/beginChair_6", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_beginChair_6"] = audio;
        });
        cc.loader.loadRes("sound/tips/beginChair_7", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_beginChair_7"] = audio;
        });
        cc.loader.loadRes("sound/tips/beginChair_8", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_beginChair_8"] = audio;
        });
        cc.loader.loadRes("sound/tips/BankerAni", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_BankerAni"] = audio;
        });
        cc.loader.loadRes("sound/tips/BankerAniStop", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_BankerAniStop"] = audio;
        });
        cc.loader.loadRes("sound/tips/timer10s", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_timer10s"] = audio;
        });
        cc.loader.loadRes("sound/tips/fapai", function (err, audio) {
            window.DKTools.audioEG.audioList["tips_fapai"] = audio;
        });
    },

    showGameStart:function(){
        this.gameStartBg.runAction(cc.sequence(cc.delayTime(2),cc.fadeOut(0.5),cc.callFunc(function () {
            this.gameStartBg.active = false;
            window.DKTools.audioEG.playBg("hallBgm");
        },this)));
    },
});
